<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { getMemberStatisticsService } from '@/api/report'

const props = defineProps({
  dateRange: {
    type: Object,
    required: true
  }
})

const chart = ref(null) // 获取DOM引用
let myChart = null // 持久化图表实例
const dateList = ref() // 日期列表
const totalMemberList = ref() // 每日会员总数列表
const newMemberList = ref() // 每日新增会员数列表

const getMemberStatistics = async () => {
  const res = await getMemberStatisticsService(props.dateRange)
  dateList.value = res.data.data.dateList
  totalMemberList.value = res.data.data.totalMemberList
  newMemberList.value = res.data.data.newMemberList
  updateChart()
}

// 初始化图表基础配置
const initChart = () => {
  myChart = echarts.init(chart.value)
  const baseOption = {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        let result = params[0].axisValue + '<br/>'
        params.forEach((item) => {
          result += `${item.marker}${item.seriesName}：<b>${item.value}</b><br/>`
        })
        return result
      }
    },
    legend: {
      data: ['会员总数', '新增会员数']
    },
    grid: {
      left: '1%',
      right: '1%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false
    },
    yAxis: {
      type: 'value',
      minInterval: 1 // 最小间隔为1
    },
    series: [
      {
        name: '会员总数',
        type: 'line',
        smooth: true
      },
      {
        name: '新增会员数',
        type: 'line',
        smooth: true
      }
    ]
  }

  myChart.setOption(baseOption)
}

// 更新图表数据
const updateChart = () => {
  const option = {
    xAxis: {
      data: dateList.value
    },
    series: [
      {
        data: totalMemberList.value
      },
      {
        data: newMemberList.value
      }
    ]
  }
  myChart.setOption(option)
}

onMounted(() => {
  initChart()
})

watch(() => props.dateRange, getMemberStatistics, { immediate: true })
</script>

<template>
  <div ref="chart" style="width: 100%; height: 350px"></div>
</template>
